package com.mall.websocket;
import lombok.extern.slf4j.Slf4j;
import javax.websocket.Session;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
@Slf4j
public class SendMsgTool {
   /**
    * 发送消息，实践表明，每次浏览器刷新，session会发生变化。
    * 
    * @param session
    * @param message
    */
   public static void SendMessage(Session session, String message) {
      try {
//            session.getBasicRemote().sendText(String.format("%s (From Server，Session ID=%s)",message,session.getId()));
         session.getBasicRemote().sendText(message);
      } catch (IOException e) {
         log.error("发送消息出错：{}", e.getMessage());
         e.printStackTrace();
      }
   }
   /**
    * 群发消息
    * 
    * @param message
    * @throws IOException
    */
   public static void BroadCastInfo(String message, CopyOnWriteArraySet<Session> SessionSet) {
      try {
         for (Session session : SessionSet) {
            if (session.isOpen()) {
               SendMessage(session, message);
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
   /**
    * 指定Session发送消息
    * 
    * @param sessionId
    * @param message
    * @throws IOException
    */
   public static void SendMessage(String message, String sessionId, CopyOnWriteArraySet<Session> SessionSet) {
      try {
         Session session = null;
         for (Session s : SessionSet) {
            if (s.getId().equals(sessionId)) {
               session = s;
               break;
            }
         }
         if (session != null) {
            SendMessage(session, message);
         } else {
            log.warn("没有找到你指定ID的会话：{}", sessionId);
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}
